import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { LiveDataStore } from "./LiveDataStore";
import { QuestionStore } from "./QuestionStore";
import { SignInStore } from "./SignInStore";
import { useOnlineTimer } from "./OnlineTimer";

const useLiveControl = defineStore("liveControl", () => {
  let checkTimer: NodeJS.Timeout | null = null;
  const isLiveEnd = ref(false);
  const setIsLiveEnd = (value: boolean) => {
    isLiveEnd.value = value;
  };
  const initWatcher = (
    liveDataStore: LiveDataStore,
    questionStore: QuestionStore,
    signinStore: SignInStore
  ) => {
    //根据streamEndTime、sigin的时间、question的时间判断是否结束
    if (checkTimer) {
      clearInterval(checkTimer);
    }
    checkTimer = setInterval(() => {
      const { streamEndTime } = liveDataStore.roomData;
      const now = Date.now();
      const endTime = new Date(streamEndTime).getTime();
      if (now < endTime) {
        return;
      }
      useOnlineTimer().endOnlineUpdater()
      if (questionStore.isVisible) {
        return;
      }
      // if (signinStore.isVisible) {
      //   return;
      // }
      setIsLiveEnd(true);
      // location.reload()
    }, 1000);
  };
  const endWatcher = () => {
    if (checkTimer) {
      clearInterval(checkTimer);
    }
  };
  return { isLiveEnd, setIsLiveEnd, initWatcher, endWatcher };
});

export { useLiveControl };

export type LiveControlStore = ReturnType<typeof useLiveControl>;
